package com.axonactive.yolo.service.implement;

import static com.axonactive.yolo.dao.jpa.implement.AirlineSpecification.findAirlineCodeLike;
import static com.axonactive.yolo.dao.jpa.implement.AirlineSpecification.findAirlineTokenLike;
import static com.axonactive.yolo.dao.jpa.implement.AirlineSpecification.findFirstAirlineCharacterLike;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.axonactive.yolo.dao.interfaces.AirlineRepository;
import com.axonactive.yolo.domain.Airline;
import com.axonactive.yolo.service.interfaces.AirlineService;

@Service
public class AirlineServiceImpl implements AirlineService {

	@Resource
	private AirlineRepository airlineRepository;

	@Transactional
//	@CacheEvict(value="listAirlineCache", allEntries = true)
	public List<Airline> findAll() {
		return airlineRepository.findAll();
	}

	@Transactional(readOnly = true)
//	@Cacheable(value="listAirlineCache", key="#token")
	public List<Airline> searchByToken(String token, int pageIndex) {
		// TODO Auto-generated method stub
		Page<Airline> requestedPage = airlineRepository.findAll(
				findAirlineTokenLike(token),
				constructPageSpecification(pageIndex));
		return requestedPage.getContent();
	}

	@Transactional(readOnly = true)
//	@Cacheable(value="listAirlineCache", key="#firstChar")
	public List<Airline> searchByFirstCharacter(String firstChar, int pageIndex) {

		Page<Airline> requestedPage = airlineRepository.findAll(
				findFirstAirlineCharacterLike(firstChar),
				constructPageSpecification(pageIndex));
		return requestedPage.getContent();
	}

	@Transactional(readOnly = true)
//	@Cacheable(value="listAirlineCache", key="#code")
	public List<Airline> searchByCode(String code, int pageIndex) {

		Page<Airline> requestedPage = airlineRepository.findAll(
				findAirlineCodeLike(code),
				constructPageSpecification(pageIndex));
		return requestedPage.getContent();
	}

	/**
	 * Returns a new object which specifies the the wanted result page.
	 * 
	 * @param pageIndex
	 *            The index of the wanted result page
	 * @return
	 */
	private Pageable constructPageSpecification(int pageIndex) {
		int numberOfResult = 10;
		Pageable pageSpecification = new PageRequest(pageIndex, numberOfResult,
				sortByLastNameASC());
		return pageSpecification;
	}

	/**
	 * Returns a Sort object which sorts airline in descending order by using
	 * the name.
	 * 
	 * @return
	 */
	private Sort sortByLastNameASC() {
		return new Sort(Sort.Direction.ASC, "name");
	}
}
